<?php

namespace App\Http\Models;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Support\Facades\Session;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{

    use Authenticatable,
        CanResetPassword;

    protected $table = 'tcustomer';
    protected $fillable = ['CName', 'CMobile', 'CPwd', 'CName', 'CWebChatID', 'CAmount'];
    protected $hidden = ['CPwd', 'remember_token'];
    public static $session_key = 'customer_id';
    public static $rule = array(
        'CName' => 'required|between:1,20',
        'CMobile' => 'required|numeric|digits:11|unique:tcustomer',
        'CPwd' => 'required|between:6,20',
        'CWebChatID' => 'required|between:1,255'
    );


    /**
     * 登陆
     */
    public static function loginAttempt($input)
    {
        $input = array_only($input, array('CWebChatID'));
        $user = self::where($input)->where('CWebChatID', '!=', '')->first();
        if ($user) {
            Session::put(self::$session_key, $user->CID);
            return true;
        } else {

            return false;
        }
    }

    public static function Check()
    {

        //Session::put(self::$session_key, 185);
        //Session::flush();
        // var_dump(Session::get(self::$session_key));
        if (Session::get(self::$session_key)) {
            return true;
        } else {
            $input['CWebChatID'] = Session::get('CWebChatID');

            if (!User::loginAttempt($input)) {
                return false;
            }

            return true;
        }
    }

    /**
     * 获取当前登录用户
     */
    public static function Auth()
    {
        return self::where('CID', Session::get(self::$session_key))->first();
    }

    /*
     * 创建或更新用户
     */
    public function doSave($input = array())
    {
        $id = array_pull($input, 'CID');

        if ($id) {
            $input = array_only($input, array('CSex', 'CName', 'CAmount'));

            return self::where('CID', $id)->update($input);
        } else {
            $input = array_only($input, array('CMobile', 'CPwd', 'CName', 'CWebChatID', 'CSex', 'CName'));
            $input['CPwd'] = md5($input['CPwd']);
            $user = self::create($input);
            Session::put(self::$session_key, $user->id);//返回是ID
            return $user;
        }
    }

    public function bindingCheck($mobile, $pwd)
    {
        return self::where('CMobile', $mobile)->where('CPwd', md5($pwd))->first();
    }

    public function binding($user)
    {
        return self::where('CID', $user->CID)->update(array('CWebChatID' => Session::get('CWebChatID')));
    }

}
